package cn.iclass.modules.sys.service.impl;

import cn.iclass.common.constant.RedisKeys;
import cn.iclass.common.param.BaseQueryParam;
import cn.iclass.common.utils.PageUtils;
import cn.iclass.modules.sys.dao.SysConfigDao;
import cn.iclass.modules.sys.entity.SysConfigEntity;
import cn.iclass.modules.sys.service.SysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @Description: 系统配置
 * @Author: alan
 * @Date: 2019/6/10 5:24 PM
 */
@Service("sysConfigService")
@CacheConfig(cacheNames = RedisKeys.SYS_CONFIG)
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {
	@Resource
	private SysConfigDao sysConfigDao;

	@Override
	public PageUtils queryPage(BaseQueryParam param, String paramKey) {
		IPage<SysConfigEntity> page = this.page(
				new Page<>(param.getCurrent(), param.getSize()),
				new QueryWrapper<SysConfigEntity>().lambda()
						.like(StringUtils.isNotBlank(paramKey), SysConfigEntity::getParamKey, paramKey)
						.eq(SysConfigEntity::getDeleted, 0)
		);

		return new PageUtils(page);
	}

	@Override
	@CachePut(key = "#config.id")
	@Transactional(rollbackFor = Exception.class)
	public boolean saveConfig(SysConfigEntity config) {
		sysConfigDao.insert(config);
		return Boolean.TRUE;
	}

	@Override
	@CachePut(key = "#config.id")
	@Transactional(rollbackFor = Exception.class)
	public void update(SysConfigEntity config) {
		sysConfigDao.updateById(config);
	}


	@Override
	@CacheEvict(allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] ids) {
		this.removeByIds(Arrays.asList(ids));
	}

	@Override
	public String getValue(String key) {
		SysConfigEntity config = baseMapper.queryByKey(key);
		return config == null ? null : config.getParamValue();
	}
}
